package chapter03;

/**
 * @ClassName Recursion
 * @Description: 递归计算阶乘和
 * @Author: WangWenpeng
 * @date: 15:16 2021/8/29
 * @Version 1.0
 */
public class Recursion {

    /**
     * 1-num的阶乘和
     */
    public static int sumFactorial(int num) {
        int ans = 0;
        for (int i = 1; i <= num; i++) {
            ans += factorial(i);
        }
        return ans;
    }

    //阶乘方法
    private static int factorial(int num) {
        int ans = 1;
        for (int i = 1; i <= num; i++) {
            ans *= i;
        }
        return ans;
    }

    /**
     * 高效的计算方法
     */
    private static int efficient(int num) {
        int ans = 0;
        int cur = 1;
        for (int i = 1; i <= num; i++) {
            cur = cur * i;
            ans = ans + cur;
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(sumFactorial(10));
        System.out.println(efficient(10));
        System.out.println(getFactorial(10));
    }

    /**
     * 递归获取给定数字的阶乘
     */
    public static int getFactorial(int num) {
        if (num == 0) {
            return 1;
        }
        return num * getFactorial(num - 1);
    }
}
